//: [Previous](@previous)

import Foundation

let volunteerCounts = [1,2,40,32,2,53,77,13]
let voluntResult = volunteerCounts.sorted { a, b in
    //这样排序表示从小到大排序
    return a < b
}

print(voluntResult)

//向sorted方法传递一个函数,规定排序规则
func sortAscending(_ i:Int,_ j:Int) -> Bool{
    return i < j
}

let volunteersSorted = volunteerCounts.sorted(by: sortAscending(_:_:))
print(volunteersSorted)


//利用参数的快捷语法来简化闭包
/**
 $0 表示第一个参数
 $1 表示第二个参数
 */
let volunteersSorted2 = volunteerCounts.sorted(by: { $0 < $1 })
print(volunteersSorted2)


/**
 作为函数最后一个参数的内联闭包
 省略两个圆括号,直接用花括号包含闭包代码
 */

let volunteersSorted3 = volunteerCounts.sorted { $0 < $1 }
print(volunteersSorted3)

//函数作为其他函数的返回值
func maketowngrand() -> (Int,Int) -> Int {
    func buildRoads(byAddingLights lights:Int,
                    toExistingLights existingLights:Int) -> Int{
        return lights + existingLights
    }
    return buildRoads(byAddingLights:toExistingLights:)
}

var stoplights = 4
let townPlanByAddingLightsToExistingLights = maketowngrand()

stoplights = townPlanByAddingLightsToExistingLights(4, stoplights)
print("Knowhere has \(stoplights) stoplights.")


//高阶函数
//高阶函数至少接受一个函数作为输入。

//map(:)
let precinctPopulations = [1244,2021,2157]

//map函数后的闭包,对数组中的每个值进行了处理,并返回,然后map函数返回一个新的数组
let projectedPopulations = precinctPopulations.map { population -> Int in
    return population * 2
}

print(projectedPopulations)

//filter(:)
//可以对Array类型进行调用。它也接收一个闭包表达式作为参数，目的是基于某些条件过滤数组。结果数组会包包含数组中通过测试的值。
let bigProjections = projectedPopulations.filter { projection -> Bool in
    return projection > 4000
}

print(bigProjections)

//resuce(_:_:)
let totalProjection = projectedPopulations.reduce(0) { partialResult, precinctProjection in
    return partialResult + precinctProjection
}

print(totalProjection)


//练习
let test1 = volunteerCounts.sorted()
print(test1)

//练习
let test2 = projectedPopulations.reduce(0) { $0 + $1 }
print(test2)
